using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace stsdev {
  public class WebPartBuilder {

    private static List<string> WebPartNames = new List<string>();

    public static void CreateWebPart(string WebPartName) {

      string WebPartSourceFilePath = WebPartName + ".cs";
      FileStream webpart_cs = File.Create(WebPartSourceFilePath);
      StreamWriter webpart_cs_writer = new StreamWriter(webpart_cs);
      string webpart_content = Properties.Resources.WebPart_cs;
      webpart_content = webpart_content.Replace("@SolutionName", SolutionBuilder.SolutionName);
      webpart_content = webpart_content.Replace("@ClassName", WebPartName);
      webpart_cs_writer.Write(webpart_content);
      webpart_cs_writer.Dispose();
      webpart_cs.Dispose();
      ProjectFileBuilder.AddSourceFile(WebPartSourceFilePath);

      WebPartDescriptionBuilder.Create(WebPartName);

      WebPartNames.Add(WebPartName);
    }

    public static void CreateWebPartFeature() {
      FeatureBuilder.CreateElementManifest("WebParts.xml", ElementsWriterCallback);      
      FeatureBuilder.Create(SolutionBuilder.SolutionName, FeatureScopeEnum.Site, false);      
    }

    private static void ElementsWriterCallback(XmlWriter writer) {
      writer.WriteStartElement("Module");
      writer.WriteAttributeString("Name", SolutionBuilder.SolutionName);
      writer.WriteAttributeString("List", "113");
      writer.WriteAttributeString("Url", "_catalogs/wp");
      writer.WriteAttributeString("Path", "WebParts");
      writer.WriteAttributeString("RootWebOnly", "True");

      foreach (string WebPartName in WebPartNames) {
        writer.WriteStartElement("File");
        writer.WriteAttributeString("Url", WebPartName + ".webpart");
        writer.WriteAttributeString("Type", "GhostableInLibrary");
        writer.WriteStartElement("Property");
        writer.WriteAttributeString("Name", "Group");
        writer.WriteAttributeString("Value", SolutionBuilder.SolutionName);
        writer.WriteEndElement(); // </Property>
        writer.WriteEndElement(); // </File>
      }      
      
      writer.WriteEndElement(); // </Module>
    }
  }
}
